<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello word</title>
</head>
<body>
hello word
</body>

<script type="text/javascript">

    var websocket = null;
    var host = window.location.host;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://" + host + "/ws");
    }
    else {
        alert("Not Support WebSocket!");
    }


    //连接发生错误的回调方法
    websocket.onerror = function () {
    };

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        alert("连接成功");
        websocket.send("hello xss");
    }

    //接收到消息的回调方法
    // 收到服务器发送的消息
    websocket.onmessage = function (event) {
        alert(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {

    }


    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }
</script>
</html>